<?php
	
	mysql_connect("127.0.0.1","root","123") or die(mysql_error());
	
	mysql_select_db("shop") or die(mysql_error());
	
	//read the post from paypal system and add 'cmd'
	$req	=	'cmd=_notify-validate';
	foreach	($_POST	as $key=>$value)	{
		$value	=	urlencode(stripslashes($value));
		$req	.=	"&$key=$value";
	}
	
	//post to paypal system to validate
	$header	=	"POST /cgi-bin/webscr HTTP/1.0\r\n";
	$header	.=	"Content-Type:application/x-www-form-urlencoded\r\n";
	$header	.=	"Content-Length:".strlen($req)."\r\n\r\n";
	
	$fp	=	fsockopen('ssl://www.paypal.com',443,$errno,$errstr,30);
	
	if(!$fp){
		//HTTP ERROR
		echo 'error';die();
	}else{
		fputs($fp,$header.$req);
		while(!feof($fp)){
			$res	=	fgets($fp,1024);
			if(strcmp($res,"VERIFIED")	==	0){
				//PAYMENT VELIDATED AND VERIFIED!
				$email	=	$_POST['payer_email'];
				$password	=	mt_rand(1000,9999);
				mysql_query("INSERT INTO gameboy90_users (email,password) VALUES ('". mysql_escape_string($email) ."', '".md5($password) ."' ) ") or die(mysql_error());
				
				$to	=	$email;
				$subject	=	'Download Area|Login Credentials';
				$message	=	'
					Thank you for your purchase
					Your account infomation:
					------------------------
					Email:'.$email.'
					Password:'.$password.'
					------------------------
					
					You can now login at http://gameboy90.gicp.net/shop';
					
					$headers	=	'From:noreply@gameboy90.gicp.net'."\r\n";
					
					mail($to,$subject,$message,$headers);
					
					;
				
				
			}else if(strcmp($res,"INVALID")	==	0){
				//PAYMENT INVALID AND INVESTIGATE MANUALY!
				$email	=	$_POST['payer_email'];
				$password	=	mt_rand(1000,9999);
				mysql_query("INSERT INTO gameboy90_users (email, password) VALUES('". mysql_escape_string($email) ."', '".md5($password)."' ) ") or die(mysql_error());
				$to	=	'invalid@gameboy90.gicp.net';
				$subject	=	'Download Area|Invalid Payment';
				$message	=	'
					Dear Administrator,
					A payment has been made but is flagged as INVALID.
					Please varify the payment manualy and contact the buyer.
					
					Buyer email:'.$email.'
					
				';
				
				$headers	=	'From:noreply@gameboy90.gicp.net'."\r\n";
				mail($to,$subject,$message,$headers);
				
			}
		}
		
		fclose($fp);
		
	}
	
		
?>